import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {CIModifyInfo} from './company-info-modify.class'

@Injectable()
export class CIModifyService {

  constructor(private _http: Http) {
  }

  getUserOriginInfo(url): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url,{}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  getUserInfo(url): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url,{}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }


  submit(url: string, ciModifyInfo: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify(ciModifyInfo), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      if (error.status > 200) {
        errMsg = '网络异常';
      } else {
        errMsg = '无法获取数据';
      }
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    return Promise.reject(errMsg);
  }
}
